<template>
  <view class="px-15 py-8 bgf disFlxAC">
    <view style="flex: 1">
      <UniSearchBar
        v-model.trim="params.keyword"
        placeholder="姓名/手机号/单位"
        cancelButton="none"
        radius="35"
        bgColor="#F5F5F5"
        @confirm="searchFnc"
        @clear="resetFnc"
      ></UniSearchBar>
    </view>
    <view v-if="showFilter" class="pl-15 py-6" @click="toTypeSelection">
      <image src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/more.png" style="width: 40rpx; height: 40rpx" />
    </view>
  </view>
  <view class="linh-40 px-15 fz-14 disFlxJS" style="background-color: #f5f5f5">
    <view>
      <text>已选 {{ selectPersonNumber + '/' + totalNumber.personNumber }} 人</text>
      <text class="pl-15">{{ selectCompanyNumber + '/' + totalNumber.companyNumber }} 单位</text>
    </view>
    <view v-if="showClear" style="color: #aaabab" @click="delAll">清空名单</view>
  </view>
</template>

<script setup lang="ts">
  import UniSearchBar from '@/uni_modules/uni-search-bar/components/uni-search-bar/uni-search-bar.vue';
  import { useDebounceFn } from '@/hooks/core/useDebounceFn';
  import { reactive, ref, unref, computed } from 'vue';
  import { useAdminStoreWithOut } from '@/store/modules/admin';
  import { uniq, compact } from 'lodash-es';
  import { propTypes } from '@/utils/propTypes';
  import { navigateTo } from '@/router';
  import type { TypeSelectedItem } from '@/router/types/modules';
  import type { SearchUserData } from '@/api/admin/types';
  import { dictAllList, getClassTypeList } from '@/api';
  import dictionary from '@/utils/dictionary';
  import type { ClassTypeListResult } from '@/api/indexTypes';

  const props = defineProps({
    showClear: propTypes.bool.def(false), // 是否显示清空按钮
    showFilter: propTypes.bool.def(true), // 是否显示过滤条件
  });
  const emits = defineEmits(['search', 'openDelAll']);

  const useAdmin = useAdminStoreWithOut();
  // 总用户数和总公司数
  const totalNumber = computed(() => {
    return useAdmin.totalNumber;
  });
  // 获取已选人员数量
  const selectPersonNumber = computed(() => {
    return useAdmin.checkedUserList.length;
  });
  // 获取已选公司数量
  const selectCompanyNumber = computed(() => {
    let companyNameList = useAdmin.checkedUserList.map((v) => v.companyName);
    companyNameList = compact(uniq(companyNameList)); // 去重 + 过滤null
    return companyNameList.length;
  });
  const delAll = () => {
    emits('openDelAll');
  };

  const params = reactive<SearchUserData>({
    current: 1,
    size: 999,
    keyword: undefined,
    levelIds: [], // 职务
    industryIds: [], // 行业
    applyType: [], // 用户类型
    groupIds: [], // 用户标签
    memberStateIds: [], // 会员状态
    paymentStatusIds: [], // 缴费状态
    initRoleIds: [], // 单位身份
  });
  const submit = useDebounceFn(() => emits('search', params), 500, { immediate: true });
  const resetFnc = () => {
    params.keyword = '';
    searchFnc();
  };
  const searchFnc = () => {
    if (
      params.keyword ||
      params?.levelIds?.length ||
      params?.industryIds?.length ||
      params?.applyType?.length ||
      params?.groupIds?.length ||
      params?.memberStateIds?.length ||
      params?.paymentStatusIds?.length ||
      params?.initRoleIds?.length
    ) {
      params.size = 999;
    } else {
      params.size = 10;
    }
    submit();
  };

  // 跳转多条件筛选人员页面
  const typeSelected = ref<TypeSelectedItem[]>([]);
  const toTypeSelection = () => {
    navigateTo({
      name: 'typeSelection',
      options: {
        localData: unref(localData),
        selected: unref(typeSelected),
        success: (arr) => {
          typeSelected.value = arr;
          // 获取职务
          params.levelIds = arr.filter((v) => v.key === 'memberLevel').map((v) => v.id);
          // 获取行业
          params.industryIds = arr.filter((v) => v.key === 'industryId').map((v) => v.id);
          // 获取用户类型
          params.applyType = arr.filter((v) => v.key === 'applyType').map((v) => v.id);
          // 获取用户标签
          params.groupIds = arr.filter((v) => v.key === 'memberGroup').map((v) => v.id);
          // 获取会员状态
          params.memberStateIds = arr.filter((v) => v.key === 'memberState').map((v) => v.id);
          // 获取缴费状态
          params.paymentStatusIds = arr.filter((v) => v.key === 'hydw_jfzt').map((v) => v.id);
          // 获取单位身份
          params.initRoleIds = arr.filter((v) => v.key === 'unitLevel').map((v) => v.id);

          searchFnc();
        },
      },
    });
  };

  /** 重组类型数据格式 */
  async function regroupClassTypeList() {
    const typeList = await getClassTypeList(['memberLevel', 'industryId', 'memberGroup']);
    return typeList.reduce((obj, v) => {
      obj[v.key] = v;
      return obj;
    }, {} as Recordable<ClassTypeListResult>);
  }

  const localData = ref<ClassTypeListResult[]>([]);
  const _getLocalData = async () => {
    const { memberLevel, industryId, memberGroup } = await regroupClassTypeList(); // 获取职务 + 行业 + 用户标签
    const hydw_jfzt = await memberPayState();
    localData.value.push(industryId); // 行业
    localData.value.push(memberGroup); // 用户标签
    localData.value.push(applyType()); // 获取用户类型
    localData.value.push(memberState()); // 获取会员状态
    localData.value.push(memberLevel); // 职务
    localData.value.push(hydw_jfzt); // 获取缴费状态
    localData.value.push(unitLevel()); // 单位身份
  };

  const memberState = () => {
    return {
      key: 'memberState',
      name: '会员状态',
      list: [
        { id: 1, name: '正常' },
        { id: 0, name: '退会' },
      ],
    } as ClassTypeListResult;
  };

  async function memberPayState() {
    const { hydw_jfzt } = await dictAllList('hydw_jfzt');
    return {
      key: 'hydw_jfzt',
      name: '缴费状态',
      list: hydw_jfzt.map((v) => {
        return {
          id: Number(v.dictValue),
          name: v.dictLabel,
        };
      }),
    } as ClassTypeListResult;
  }

  function unitLevel() {
    const _r = dictionary.getLocal('memberLevel');
    return {
      key: 'unitLevel',
      name: '单位身份',
      list: _r.map((v, i) => {
        return {
          id: Number(v.dictValue),
          name: v.dictValue !== '0' ? `会员-${v.dictLabel}` : v.dictLabel,
        };
      }),
    } as ClassTypeListResult;
  }

  function applyType() {
    const _r = dictionary.getLocal('applyType');
    return {
      key: 'applyType',
      name: '用户类型',
      list: _r.map((v) => {
        return {
          id: Number(v.dictValue),
          name: v.dictLabel,
        };
      }),
    } as ClassTypeListResult;
  }

  _getLocalData();
</script>

<style lang="scss" scoped></style>
